package com.learn.dataStructor.linked;

/**
 * @Author: Yinliu Hao
 * @Description:
 * @Date: Created in 2022/2/9 22:21
 * @Modify By:
 */
//循环链表
public class MyCycleLink {

    protected CycleNode root;
    protected int count;

    public MyCycleLink(){

    }

    public MyCycleLink(CycleNode root){
        this.root = root;
        root.next = root;
        this.count = 1;
    }

    //初始化约瑟夫环专用
    public MyCycleLink(int count){
        for(int i=1;i<=count;i++){
            add(new CycleNode(i));
        }
    }

    public void add(CycleNode node){
        if(null == root){
            this.root = node;
            root.next = root;
            this.count = 1;
        }else{
            CycleNode node1 = root;
            while(node1.next!=root){
                node1 = node1.next;
            }
            node1.next = node;
            node.next = root;
            count++;
        }
    }

    public void print(){
        System.out.println("count="+count);
        CycleNode node = root;
        do{
            System.out.println(node.data);
            node = node.next;
        }while(node!=root);
    }


    public static void main(String[] args) throws Exception{

        fun2();

    }

    public static void fun1() throws Exception{
        MyCycleLink link = new MyCycleLink();
        link.add(new CycleNode("1"));
        link.add(new CycleNode("2"));
        link.add(new CycleNode("3"));
        link.add(new CycleNode("4"));
        link.add(new CycleNode("5"));
        link.print();
        //node.print();
        System.out.println("-----------------");
        //node.removeAfter();
        //node.print();
        System.out.println("-----------------");
        //node.insertAfter(new CycleNode("7"));
        //node.print();
    }

    public static void fun2(){
        MyCycleLink link = new MyCycleLink(10);
        link.print();
    }

    public static MyCycleLink init(){

        return null;
    }

}

class CycleNode{
    Object data;
    CycleNode next;

    public CycleNode(Object data,CycleNode next){
        this.data = data;
        this.next = next;
    }

    public CycleNode(Object data){
        this.data = data;
        this.next = null;
    }

    //这个add是加在后面，LinkNode的add是加在末尾。CycleNode的add在不知道root的情况下无法加到末尾
    public void add(CycleNode node){
        node.next = this.next;
        this.next = node;
    }

    public void removeAfter() throws Exception{
        if(this.next!=this){
            this.next=this.next.next;
        }else{
            throw new Exception("当前链表中只有一个节点");
        }
    }

 /*   public void insertAfter(CycleNode node){
        node.next = this.next;
        this.next = node;
    }*/

    /*public void print(){
        System.out.println(this.data);
        if(null!=this.next){
            this.next.print();
        }

    }*/

}